{extend name="base" /}
{block name="css"}
<link rel="stylesheet" href="__PUBLIC__/plugins/layui/layui_ext/dtree/dtree.css">
<link rel="stylesheet" href="__PUBLIC__/plugins/layui/layui_ext/dtree/font/dtreefont.css">
<style>
    .choice-user-dvi {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 10px 20px;
    }

    .choice-user-dvi:hover {
        cursor: pointer;
        background: #eee;
    }

    .choice-user-dvi-img {
        width: 30px;
        height: 30px;
        display: block;
        margin: 0 10px;
    }

    .choice-user-dvi-text {
        display: flex;
        align-items: center;
        font-size: 14px;
    }

    .no-choice-user {
        text-align: center;
        color: #999;
    }
    .layui-tab-item,.admin-main{
        padding-bottom: 0;
        margin-bottom: 0;
    }
    .listBox{
        overflow: hidden;
    }
</style>
{/block}
{block name="body"}
<div class="admin-main layui-form layui-field-box">
    <div class="layui-form-item">
        <label class="layui-form-label" style="width: auto;padding: 9px 0px">搜索:</label>
        <div class="layui-input-block" style="margin-left: 70px">
            <div class="tags" id="tags" style="width: 80%;margin: 0px;padding: 0px 10px;">
                <input type="text" name="nickname" id="inputTags" placeholder="请输入用户名" autocomplete="off"/>
                <input type="hidden" name="tags-content" value=""/>
            </div>
        </div>
    </div>
    <div class="layui-tab layui-tab-card" lay-filter="choicecard">
        <ul class="layui-tab-title">
            {switch $scene}
            {case all}
            <li class="layui-this">组织</li>
            <li>人员</li>
            {/case}
            {case group}
            <li class="layui-this">组织</li>
            {/case}
            {case user}
            <li class="layui-this">人员</li>
            <!-- <li>群众</li> -->
            {/case}
            {/switch}
        </ul>
        <div class="layui-tab-content" style="min-height: 100px;">
            {switch $scene}
            {case all}
            <div class="layui-tab-item layui-show">
                <div class="listBox">
                    <ul id="demoTree" data-id="0"></ul>
                </div>
            </div>
            <div class="layui-tab-item">
                <div style="display: flex;flex-direction: row;">
                    <div class="listBox">
                        <ul id="userDepTree" style="width:70%;" data-id="0"></ul>
                    </div>
                    <div id="personnel" style="width: 250px;border-left: 1px solid #eee;">
                        <div class="no-choice-user">点击左侧组织获取人员列表</div>
                    </div>
                </div>
            </div>
            {/case}
            {case group}
            <div class="layui-tab-item layui-show">
                <div class="listBox">
                    <ul id="demoTree" data-id="0"></ul>
                </div>
            </div>
            {/case}
            {case user}
            <div class="layui-tab-item layui-show">
                <div style="display: flex;flex-direction: row;">
                    <div class="listBox">
                        <ul id="userDepTree" style="width:70%;" data-id="0"></ul>
                    </div>
                    <div id="personnel" class="listBox" style="width: 250px;border-left: 1px solid #eee;">
                        <div class="no-choice-user">点击左侧组织获取人员列表</div>
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-clear">
                    <table class="layui-hide" id="demo" lay-filter="test"></table>
                </div>
            </div>
            {/case}
            {/switch}
        </div>
    </div>
</div>

{/block}
{block name="js"}
<script>
    var selected_appoint_user = []
        , selected_appoint_group = []
        , tags = [];
    var TagsObj = {};

    function get_selected_data() {
        let data = {};
        console.log('selected_appoint_group106', selected_appoint_group)
        data.user = selected_appoint_user;
        data.group = selected_appoint_group;
        data.tags = tags;
        return data;
    }

    function del_selected_data(param) {
        // let exist_group = selected_appoint_group.indexOf(param);
        // if (exist_group > -1) {
        //     selected_appoint_group.splice(exist_group, 1);
        // }
        // let exist_user = selected_appoint_user.indexOf(param);
        // if (exist_user > -1) {
        //     selected_appoint_user.splice(exist_user, 1);
        // }
        // let exist_tags = tags.indexOf(param);
        // if (exist_tags > -1) {
        //     tags.splice(exist_tags, 1);
        // }
    }

    layui.extend({
        inputTags: '/plugins/layui/inputTags/inputTags',
        yutons_sug: '/plugins/layui/yutons-mods/yutons_sug',
        dtree: '/plugins/layui/layui_ext/dtree/dtree',
    }).use(['element', 'inputTags', 'dtree', 'yutons_sug', 'table'], function () {
        var element = layui.element
            , form = layui.form
            , layer = layui.layer
            , jq = $ = layui.jquery
            , inputTags = layui.inputTags
            , dtree = layui.dtree
            , table = layui.table
            , yutons_sug = layui.yutons_sug;


        var wh = jq(window).height();
        console.log('wh', wh)
        jq('.listBox').css({"height":(wh-160)+"px","overflow-y":'scroll'});

        var $node = '';
        var checkbarFun = {
            chooseBefore: function ($i, node) { //复选框点击前的回调。
                // console.log(node);
                $node = node;
                return true;
            }
        };

        yutons_sug.render({
            id: "inputTags",
            height: "167",
            cols: [
                [{
                    field: 'nickname',
                    title: '用户名'
                }, {
                    field: 'mobile',
                    title: '手机号'
                }, {
                    field: 'dep_name',
                    title: '部门'
                }, {
                    field: 'level_name',
                    title: '职务'
                },
                    // {
                    //                 field: 'mass',
                    //                 title: '群众'
                    //             },
                ]
            ],
            field: 'nickname',
            type: 'sugTable', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
            url: "{:url('user/getLikeUserList')}" + "?keyword=",
            remove: function (res) {
                let data = {
                    id:res.id,
                    name:res.nickname,
                    type:'user'
                };
                let index = selected_appoint_user.findIndex(res=>{
                    return res.id==data.id && res.name==data.name && res.type==data.type;
                });
                if(index<0){
                    selected_appoint_user.push(data);
                }
            }
        });

        let dataUrl = "{:url('user/departmentDtree', array('disToSub'=>$disToSub))}";
        console.log('dataUrl: ', dataUrl);
        if ("{$scene}" == 'group' || "{$scene}" == 'all') {
            var DemoTree = dtree.render({
                elem: "#demoTree",
                width: "400",
                line: true,  // 显示树线
                // icon: "-1",  // 隐藏二级图标
                url: dataUrl,
                type: "all",
                dot: false,
                checkbar: true,
                // checkbarType: "self",
                checkbarType: "no-all",
                checkbarData: 'all',
                checkbarFun: checkbarFun,
                response: {
                    parentId: 'parent_id'
                }
            });
        }

        let dataUrl2 = "{:url('user/departmentDtree')}";
        if ("{$scene}" == 'user' || "{$scene}" == 'all') {
            var userDepTree = dtree.render({
                elem: "#userDepTree",
                width: "400",
                line: true,  // 显示树线
                // icon: "-1",  // 隐藏二级图标
                url: dataUrl2,
                type: "all",
                dot: false,
            });
        }

        dtree.on("chooseDone('demoTree')", function (obj) {
            //当前点击之后触发的事件返回的值，即所有节点的信息
            for(v of obj.checkbarParams){
                //构建返回的数组（组织的）
                let data = {
                    id:v.nodeId,
                    name:v.context,
                    type:'group'
                };
                //查找返回的值是否存在同名，同id，同类型的
                let index = selected_appoint_group.findIndex(res=>{
                    return res.id==data.id && res.name==data.name && res.type==data.type;
                });
                //勾选和未勾选的判断
                if(v.checked!=1){
                    //删除对应标签
                    TagsObj.removeTag(data);
                    //返回的值存在同名，同id，同类型的，去除
                    if(index>-1){
                        selected_appoint_group.splice(index,1);
                    }
                }else{
                    //返回的值不存在同名，同id，同类型的
                    if(index<0){
                        TagsObj.addTag(data);
                        selected_appoint_group.push(data);
                    }
                }
            }
        });

        function getParentName(arr, pid) {
            if (pid > 0) {
                for (let i2 in arr) {
                    let v = arr[i2];
                    if (pid == v.nodeId) {
                        return v.context.replace('(全选)', '');
                    }
                }
            }
            return '顶级';
        }

        dtree.on("node('userDepTree')", function (param) {
            let dep_auth = {:json_encode($Think.session.dep_auth)};
            console.log(dep_auth);
            if (dep_auth[param.param.nodeId] != 1){
                layer.msg('您没有查看此组织数据的权限')
                return;
            }
            let data = {
                dep_id: param.param.nodeId
            }
            jq.post("{:url('user/choiceUser')}", data, function (res) {
                var $html = jq(res);
                if (selected_appoint_user.length > 0) {
                    for (let v of selected_appoint_user) {
                        let checked = $html.find('#selTotss' + v.id);
                        if (checked.length == 1) {
                            checked.attr('checked', true);
                            checked.prop('checked', true);
                        }
                    }
                }
                jq('#personnel').html('');
                jq('#personnel').append($html.html());
            });
        });

        jq('#personnel').on('click', '.choice-user-dvi', function (e) {
            let obj = jq(this).find('input[type=checkbox]');
            let status = obj[0].checked;
            if(e.target.nodeName=='INPUT'){
                status = !status;
            }
            console.log(selected_appoint_user);
            let data = {
                id:this.dataset.id,
                name:this.dataset.nickname,
                type:'user'
            };
            if('{$checkbar}'==false){
                TagsObj.removeTag(selected_appoint_user[0]);
                selected_appoint_user = [];
            }

            let index = selected_appoint_user.findIndex(res=>{
                return res.id==data.id && res.name==data.name && res.type==data.type;
            });

            if (status) {
                TagsObj.removeTag(data);
                selected_appoint_user.splice(index,1);
            } else {
                if('{$checkbar}'==false){
                    selected_appoint_user = [];
                    jq('input[type=checkbox]').prop('checked', false);
                }
                TagsObj.addTag(data);
                if(index<0){
                    selected_appoint_user.push(data);
                }
            }
            obj.attr('checked', !status);
            obj.prop('checked', !status);
        });

        TagsObj = inputTags.render({
            elem: '#inputTags',
            aldaBtn: true,
            count: 9999,
            showDeleted: false,
            done: function (value) {
                //console.log(value);
            },
            remove: function (value) {
                del_selected_data(value);
            }
        });

        // let url = '{:url("mass/index")}';
        // let tableData = {
        //     elem: '#demo'
        //     , url: url
        //     , defaultToolbar: []//['filter', 'print', 'exports']
        //     , title: 'list test'
        //     , cellMinWidth: 30
        //     , cols: [
        //         [{
        //             "title": "ID",
        //             "field": "id",
        //             "type": "text",
        //             "width": 80,
        //             "align": "center",
        //             "sort": false
        //         }, {
        //             "title": "姓名",
        //             "field": "nickname",
        //             "type": "text",
        //         }, {
        //             "title": "手机号",
        //             "field": "mobile",
        //             "type": "text",
        //         }]
        //     ],
        //     page: true
        //     , response: {
        //         statusCode: 1
        //     }
        //     ,id: 'testReload',
        //     done:
        //         function (res, curr, count) {
        //             currPage = curr;
        //             if (res.data.length == 0 && currPage > 1) {
        //                 //当前页数据为空自动切到前一页
        //                 active['reload'] ? active['reload'].call(this, currPage - 1) : '';
        //             }
        //             $('#testReload').find('.layui-table-body').find("table" ).find("tbody").children("tr").on('click',function(){
        //                 var id = JSON.stringify($('#testReload').find('.layui-table-body').find("table" ).find("tbody").find(".layui-table-hover").data('index'));
        //                 var obj = res.data[id];  //这里都是表格的数据
        //                 console.log('obj', obj)
        //                 // fun.openLayer(obj);
        //             })
        //         }
        // };

        // table.render(tableData);

        //行单击事件（双击事件为：rowDouble）
        table.on('row(test)', function(obj){
            var rdata = obj.data;
            console.log('rdata', rdata)
            if ('{$checkbar}' == false) {
                for (let i in tags) {
                    TagsObj.removeTag(tags[i]);
                }
                tags = [];
                selected_appoint_user = [];
            }
            let data = {
                id:rdata.id,
                name:rdata.nickname,
                type:'user'
            };

            let index = selected_appoint_user.findIndex(res=>{
                return res.id==data.id && res.name==data.name && res.type==data.type;
            });
            if (obj.tr.hasClass('layui-table-click')) {
                TagsObj.removeTag(data);
                selected_appoint_user.splice(index,1);
                obj.tr.removeClass('layui-table-click')
            } else {
                if(index<0){
                    TagsObj.addTag(data);
                    selected_appoint_user.push(data);
                }
                //标注选中样式
                if ('{$checkbar}' == false) {
                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                } else {
                    obj.tr.addClass('layui-table-click');
                }
            }
        });

    });
</script>
{/block}